﻿using MTHHelper;
using MTHModels;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.UI.WebControls.WebParts;
using System.Windows.Forms;
using thinger.DataConvertLib;

namespace MTHProject
{
    public partial class FrmRecipe : Form
    {
        public FrmRecipe(string devPath)
        {
            InitializeComponent();

            this.lbl_CurrentRecipe.Text = CommonMethods.Device.CurrentRecipe;
            this.txt_RecipeName.Text = CommonMethods.Device.CurrentRecipe;
            RefreshRecipe();
            this.devPath = devPath;
        }

        private string devPath = string.Empty;

        private string basePath = Application.StartupPath + "\\Recipe";

        private List<RecipeInfo> recipeInfos = new List<RecipeInfo>();

        private void btn_Add_Click(object sender, EventArgs e)
        {
            //非空验证
            if(this.txt_RecipeName.Text.Trim().Length == 0)
            {
                new FrmMsgBoxWithoutAck("配方名称为空，请检查", "添加配方").Show();
                return;
            }

            var info = recipeInfos.Where(c => c.RecipeName == this.txt_RecipeName.Text.Trim()).FirstOrDefault();

            if(info != null)
            {
                new FrmMsgBoxWithoutAck("当前配方名称已存在，请检查", "添加配方").Show();
                return;
            }

            var recipeInfo = GetRecipeInfo();

            bool result = AddRecipe(recipeInfo);

            if(result)
            {
                RefreshRecipe();
                new FrmMsgBoxWithoutAck("配方添加成功","添加配方").Show();
            }
            else
            {
                new FrmMsgBoxWithoutAck("配方添加失败", "添加配方").Show();
            }
        }

        private void btn_Modify_Click(object sender, EventArgs e)
        {
            //非空验证
            if (this.txt_RecipeName.Text.Trim().Length == 0)
            {
                new FrmMsgBoxWithoutAck("配方名称为空，请检查", "修改配方").Show();
                return;
            }

            var info = recipeInfos.Where(c => c.RecipeName == this.txt_RecipeName.Text.Trim()).FirstOrDefault();

            if (info == null)
            {
                new FrmMsgBoxWithoutAck("当前配方名称不存在，无法修改", "修改配方").Show();
                return;
            }

            var recipeInfo = GetRecipeInfo();

            bool result = AddRecipe(recipeInfo);

            if (result)
            {
                RefreshRecipe();
                new FrmMsgBoxWithoutAck("配方修改成功", "修改配方").Show();
            }
            else
            {
                new FrmMsgBoxWithoutAck("配方修改失败", "修改配方").Show();
            }
        }

        private void btn_Delete_Click(object sender, EventArgs e)
        {
            //非空验证
            if (this.txt_RecipeName.Text.Trim().Length == 0)
            {
                new FrmMsgBoxWithoutAck("配方名称为空，请检查", "删除配方").Show();
                return;
            }

            var info = recipeInfos.Where(c => c.RecipeName == this.txt_RecipeName.Text.Trim()).FirstOrDefault();

            if (info == null)
            {
                new FrmMsgBoxWithoutAck("当前配方名称不存在，请检查", "删除配方").Show();
                return;
            }

            DialogResult dialogResult = new FrmMsgBoxWithAck("是否确定要删除配方?", "删除配方").ShowDialog();

            if (dialogResult == DialogResult.OK)
            {
                bool result = DeleteRecipe(this.txt_RecipeName.Text.Trim());

                if (result)
                {
                    RefreshRecipe();
                    new FrmMsgBoxWithoutAck("配方删除成功", "删除配方").Show();
                }
                else
                {
                    new FrmMsgBoxWithoutAck("配方删除失败", "删除配方").Show();
                }

            }
        }

        private void btn_Apply_Click(object sender, EventArgs e)
        {
            //非空验证
            if (this.txt_RecipeName.Text.Trim().Length == 0)
            {
                new FrmMsgBoxWithoutAck("配方名称为空，请检查", "应用配方").Show();
                return;
            }

            var info = recipeInfos.Where(c => c.RecipeName == this.txt_RecipeName.Text.Trim()).FirstOrDefault();

            if (info == null)
            {
                new FrmMsgBoxWithoutAck("当前配方名称不存在，请检查", "应用配方").Show();
                return;
            }

            if(!CommonMethods.Device.IsConnected)
            {
                new FrmMsgBoxWithoutAck("请检查设备是否连接正常!", "应用配方").Show();
                return;
            }

            if (info.RecipeParam.Count == 6)
            {
                List<short> values = new List<short>();

                //添加温度和湿度的高低限
                for (int i = 0; i < 6; i++)
                {
                    values.Add(Convert.ToInt16(info.RecipeParam[i].TempHigh * 10));
                    values.Add(Convert.ToInt16(info.RecipeParam[i].TempLow * 10));
                    values.Add(Convert.ToInt16(info.RecipeParam[i].HumidityHigh * 10));
                    values.Add(Convert.ToInt16(info.RecipeParam[i].HumidityLow * 10));
                }

                //添加一些空闲的地址数值
                for (int i = 0;i < 6; i++)
                {
                    values.Add(0);
                }

                //继续添加报警启用
                for(int i = 0; i < 6; i++)
                {
                    values.Add(info.RecipeParam[i].TempAlarmEnale? (short)1:(short)0);
                    values.Add(info.RecipeParam[i].HumidityAlarmEnale ? (short)1 : (short)0);
                }

                bool result = CommonMethods.modbus.PreSetMultiRegisters(36,ByteArrayLib.GetByteArrayFromShortArray(values.ToArray(),CommonMethods.dataFormat));

                if(result)
                {
                    string recipeName = this.txt_RecipeName.Text.Trim();

                    IniConfigHelper.WriteIniData("配方参数","当前配方", recipeName, this.devPath);
                    CommonMethods.Device.CurrentRecipe = recipeName;
                    this.lbl_CurrentRecipe.Text = recipeName;

                    new FrmMsgBoxWithoutAck("配方数据写入成功", "应用配方").Show();
                }
                else
                {
                    new FrmMsgBoxWithoutAck("配方数据写入失败，请检查", "应用配方").Show();
                }

            }
            else
            {
                new FrmMsgBoxWithoutAck("配方数据不完整，请检查!", "应用配方").Show();
            }

        }

        #region 更新配方列表
        private void RefreshRecipe()
        {
            recipeInfos = GetAllRecipe();

            if(recipeInfos.Count > 0)
            {
                this.dgv_Main.Rows.Clear();

                for(int i = 0; i < recipeInfos.Count; i++)
                {
                    this.dgv_Main.Rows.Add();
                    this.dgv_Main.Rows[i].Cells[0].Value = (i+1).ToString();
                    this.dgv_Main.Rows[i].Cells[1].Value = recipeInfos[i].RecipeName;

                    if(this.txt_RecipeName.Text == recipeInfos[i].RecipeName)
                    {
                        this.dgv_Main.Rows[i].Selected = true;
                    }
                    else
                    {
                        this.dgv_Main.Rows[i].Selected = false;
                    }
                }

                if(this.dgv_Main.SelectedRows.Count > 0)
                {
                    SetRecipeInfo(this.recipeInfos[this.dgv_Main.SelectedRows[0].Index]);
                }
            }
        }
        #endregion

        #region 获取配方对象
        private RecipeInfo GetRecipeInfo()
        {
            RecipeInfo recipeInfo = new RecipeInfo();

            recipeInfo.RecipeName = this.txt_RecipeName.Text.Trim();

            recipeInfo.RecipeParam = new List<RecipeParam>()
            {
                this.recipeControl1.RecipeParam,
                this.recipeControl2.RecipeParam,
                this.recipeControl3.RecipeParam,
                this.recipeControl4.RecipeParam,
                this.recipeControl5.RecipeParam,
                this.recipeControl6.RecipeParam
            };
            return recipeInfo;
        }
        #endregion

        #region 添加配方
        private bool AddRecipe(RecipeInfo recipeInfo)
        {
            string path = basePath + "\\" + recipeInfo.RecipeName + ".ini";

            return IniConfigHelper.WriteIniData("配方","配方数据",JsonHelper.EntityToJSON(recipeInfo),path);
        }
        #endregion

        #region 获取所有配方
        private List<RecipeInfo> GetAllRecipe()
        {
            DirectoryInfo directoryInfo = new DirectoryInfo(basePath);

            List<FileInfo> fileInfos = directoryInfo.GetFiles("*.ini").ToList();

            List<RecipeInfo> recipeInfos = new List<RecipeInfo>();

            foreach (var item in fileInfos)
            {
                recipeInfos.Add(GetRecipe(item.FullName));
            }
            return recipeInfos;
        }
        #endregion

        #region 显示当前配方
        private void SetRecipeInfo(RecipeInfo recipeInfo)
        {
            this.txt_RecipeName.Text = recipeInfo.RecipeName;

            if(recipeInfo.RecipeParam.Count == 6)
            {
                this.recipeControl1.RecipeParam = recipeInfo.RecipeParam[0];
                this.recipeControl2.RecipeParam = recipeInfo.RecipeParam[1];
                this.recipeControl3.RecipeParam = recipeInfo.RecipeParam[2];
                this.recipeControl4.RecipeParam = recipeInfo.RecipeParam[3];
                this.recipeControl5.RecipeParam = recipeInfo.RecipeParam[4];
                this.recipeControl6.RecipeParam = recipeInfo.RecipeParam[5];
            }
        }
        #endregion

        #region 文件变对象
        private RecipeInfo GetRecipe(string path)
        {
            return JsonHelper.JSONToEntity<RecipeInfo>(IniConfigHelper.ReadIniData("配方", "配方数据", "", path));
        }
        #endregion

        #region 删除配方
        private bool DeleteRecipe(string recipeName)
        {
            try
            {
                File.Delete(basePath + "\\" + recipeName + ".ini");
            }
            catch (Exception)
            {
                return false;
            }
            return true;
        }
        #endregion

        #region DataGridView选中事件
        private void dgv_Main_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if(e.RowIndex >= 0)
            {
                var recipeInfo = recipeInfos[e.RowIndex];

                SetRecipeInfo(recipeInfo);
            }
        }
        #endregion

    }
}
